/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lmx.repoDomain.repository;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lmx.common.constants.CommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.common.util.NumberTool;
import com.lmx.persistence.service.DrugService;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.CustomerDrug;
import com.lmx.repoDomain.tmodel.CustomerDrugProject;
import com.lmx.repoDomain.tmodel.CustomerDrugReport;
import com.lmx.repoDomain.tmodel.CustomerDrugReportItem;
import com.lmx.repoDomain.tmodel.NursingPlanDetail;

import io.katharsis.repository.annotations.JsonApiResourceRepository;
import io.katharsis.repository.annotations.JsonApiSave;

@JsonApiResourceRepository(CustomerDrugReport.class)
@Component
public class CustomerDrugReportRepository extends BaseRepository<CustomerDrugReport> {

	@Autowired
	DrugService drugService;
	
	@PostConstruct
	public void init() {
		dslJpaService.setEntityClass(CustomerDrugReport.class);
	}

	@Override
	@JsonApiSave
	public CustomerDrugReport save(CustomerDrugReport customerDrugReport) {
		if(customerDrugReport.getErrcode()!=null){
			throw new BusinessException(null, CommonConstants.ERROR_CODE.ADD_ERROR.label(), null);
		}
		Long tenantId = ActionContextHolder.getContext().getTenantId();
		// 判断今天是否已经存在了，如果有了，返回失败，不生成记录
		if (drugService.isExistDrugReportToday(tenantId)) {
			throw new BusinessException(null, CommonConstants.ERROR_CODE.REPEAT_ERROR.label(), null);
		}
		
		// 获得用药提醒时间内不足的药品，保存记录
		List<CustomerDrugProject> list = drugService.getDrugReport(tenantId);
		if (list.size() <= 0) {
			throw new BusinessException(null, CommonConstants.ERROR_CODE.ADD_ERROR.label(), null);
		}
		drugService.saveDrugReport(customerDrugReport);
		
		return customerDrugReport;
	}
}
